<template>
  <div style="font-size:1rem">
    <!-- 测试数据
    <h1>FEPPAY</h1>
    <h2>传递来的参数：{{param}}</h2>
    <h2>判断是那个终端扫码：{{t}}</h2>
    -->
    <navTop :headTitle="headTitle" :showBack="showBack" :bkParam="bkParam"></navTop>
    <div class="pay_top">
      <p>请在{{minutes}}分{{seconds}}秒内完成支付功能，超时自动取消</p>
    </div>
    <div class="pay_con">
      <p>姓名：<span>{{payInfo.reg_name}}</span></p>
      <p>身份证号：<span>{{payInfo.reg_sfzh}}</span></p>
      <p>医保支付：<span>{{payInfo.zxjjzf}}<i>元</i></span></p>
      <p>账户支付：<span>{{payInfo.zhsjzf}}<i>元</i></span></p>
      <p>应付金额：<span>{{payInfo.zfje}}<i>元</i></span></p>
    </div>
    <p class="pay_way">选择支付方式:</p>
    <div class="pay_con">
      <p @click="changePay"><i class="iconfont icon-weixinzhifu"></i>微信支付<i class="iconfont icon-selected" v-show="payWay"></i></p>
      <!-- <p @click="changePay"><i class="iconfont icon-ziyuan"></i>支付宝<i class="iconfont icon-selected" v-show="!payWay"></i></p> -->
    </div>
    <button @click="perPay" class="pay_bot">立即付款</button>
    <transition name="tipMove">
      <alert-tip :alertText="alertText" v-if="showAlert" @closeTip="closeTip"></alert-tip>
    </transition>
  </div>
</template>

<script>
import navTop from '~/components/common/navTop';
import alertTip from '~/components/common/alertTip';

export default {
  data() {
    return {
      showAlert: false,
      alertText: '',
      showBack: true,
      bkParam: 'bk',
      headTitle: '处方订单支付',
      ts: this.newStore(),
      tq: this.getData(),
      param: '',
      t: 'none', // 扫码应用的标识
      minutes: 15,
      seconds: 0,
      payInfo: {
        reg_name: '测试名称',
        reg_sfzh: '123456',
        zxjjzf: '100.00',
        zhsjzf: '50.00',
        zfje: '50.00',
      },
      prepayid: {}, // 预支付信息
    };
  },
  created() {
    this.param = `${sessionStorage.getItem('pm')}`;
    this.IsWeixinOrAlipay(); // 判断是微信还是支付宝还是其他扫码
    this.getPayInfo();
  },
  components: {
    navTop, alertTip,
  },
  mounted() {
    this.timer();
  },
  methods: {
    // 获取支付订单信息
    getPayInfo() {
      const D = {
        payparam: `${this.param}`, // 支付信息参数
        apptype: `${this.t}`, // 终端类型
        domainname: `${sessionStorage.getItem('hospitalDomainname')}`,
      };
      this.tq.getPayInfo(D).then((ts) => {
        // console.log(`获取支付信息返回参数：   ${JSON.stringify(ts.d)}`);
        // alert(`获取支付信息返回参数：   ${JSON.stringify(ts.d)}`);
        this.payInfo = ts.d.DATAOBJ.DATA;
      });
    },
    IsWeixinOrAlipay() {
      const ua = window.navigator.userAgent.toLowerCase();
      // 判断是不是微信
      if (ua.indexOf('micromessenger') > 0) {
        this.t = 'wxpay';
      }
      // 判断是不是支付宝
      if (ua.indexOf('alipayclient') > 0) {
        this.t = 'alipay';
      }
    },
    //
    closeTip() {
      this.showAlert = false;
    },

    // ===================================
    // 新用户扫码，如果是微信端，静默方式请求支付，静默关注公众号，支付成功后，可以静默收到支付的模板消息
    // ===================================
    perPay() {
      const res = JSON.stringify({
        OTRequest: {
          VERSION: '1.0',
          TN: 'F27.APP.12.03',
          CLIENTID: 'YLAPP',
          RYBID: 'PAT',
          TOKEN:
            `${sessionStorage.getItem('rybToken')}`,
          DATA: {
            oid: `${this.payInfo.htoid}`,
            sfktype: `${this.payInfo.sfk_type}`, // orderPay微信注册认证后手机端支付；patVis未注册就诊时医院收银扫码支付；patReg就诊时医院收银扫码支付
            state: '', // 通过CODE传递到服务器，服务器通过state来获取
            domainname: `${sessionStorage.getItem('hospitalDomainname')}`,
            payclient: `${this.t}`, // 'wxpay', 'alipay', 'none'
            servname: `患者扫码支付药方订单(${this.payInfo.htoid})`,
            // ayid: `${this.ayid}`,
            // oaid: `${this.oaid}`,
            // servname: `测试：患者(${sessionStorage.getItem('patname')})支付药方订单(${this.orderId})`, // 某些微信名称无法正常解析为UTF8,因此放弃患者名称
            // je_sf: `${Number(this.yff) + Number(this.jgf) + Number(this.psf)}`,
            // 补充的八个参数
            // fpzt: `${this.fpzt}`, // 是否开发票
            // jyfw: `${this.jyfw}`, // 是否需要煎药服务，只有中药类别需要显示此项
            // kdfw: `${this.kdfw}`, // 是否需要快递服务
            // je_yh: `${this.je_yh}`, // 优惠金额
            // je_jyfw: `${this.jgf}`, // 煎药服务费
            // je_kdfw: `${this.psf}`, // 快递服务费
            // je_prescribe: `${this.yff}`, // 药方费（药方*数量）
            // je_ze: `${this.je_ze}`, // 需要支付的总金额（不带优惠金额）
            je_sf: `${this.payInfo.zfje}`, // 实付金额（减掉优惠金额）
          },
        },
      });
      this.spost(this.ts, '/doctor/AppMainServlet.ap', {
        '': res,
      }).then((ts) => {
        // alert(`获取prepay_id返回的参数：   ${JSON.stringify(ts.d)}`);
        this.prepayid = ts.d.DATAOBJ.DATA;
        // 调用支付流程
        this.PayMoney();
      });
    },
    onBridgeReady() {
      /*
      alert(`this.prepayid.timeStamp : ${this.prepayid.timeStamp}`);
      alert(`this.prepayid.appId : ${this.prepayid.appId}`);
      alert(`this.prepayid.nonceStr : ${this.prepayid.nonceStr}`);
      alert(`this.prepayid.package : ${this.prepayid.package}`);
      alert(`this.prepayid.signType : ${this.prepayid.signType}`);
      alert(`this.prepayid.paySign : ${this.prepayid.paySign}`);
*/
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          timeStamp: `${this.prepayid.timeStamp}`, // 时间戳，自1970年以来的秒数
          appId: `${this.prepayid.appId}`, // 公众号名称，由商户传入
          nonceStr: `${this.prepayid.nonceStr}`, // 随机串
          package: `${this.prepayid.package}`, //
          signType: `${this.prepayid.signType}`, // 微信签名方式
          paySign: `${this.prepayid.paySign}`, // 微信签名
        },
        (res) => {
          // alert(`输入密码后从微信服务器返回来的支付结果：${JSON.stringify(res)}`);
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            this.$router.push({ name: 'chufang-payOff', query: { je_sf: this.je_sf, payResult: true, payMessage: '支付成功' } });
          } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
            // this.$router.push({ name: 'payOff', query: { je_sf: this.je_sf, payResult: false, payMessage: '取消支付' } });
            this.showAlert = true;
            this.alertText = '已取消支付';
          } else {
            // this.$router.push({ name: 'payOff', query: { je_sf: this.je_sf, payResult: false, payMessage: res.err_msg } });
            this.showAlert = true;
            this.alertText = `支付失败,错误信息${res.err_msg}`;
          }
        },
      );
    },
    // 立即支付调用微信接口，生产环境使用
    PayMoney() {
      if (typeof WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
        }
      } else {
        this.onBridgeReady();
      }
    },
    changePay() {
      this.payWay = !this.payWay;
    },
    timer() {
      const _this = this;
      const time = window.setInterval(() => {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59;
          _this.minutes -= 1;
        } else if (_this.minutes === 0 && _this.seconds === 0) {
          _this.seconds = 0;
          window.clearInterval(time);
          this.$router.back(-1);
        } else {
          _this.seconds -= 1;
        }
      }, 1000);
    },
  },
  destroyed() {
    this.$root.showfooter = true;
  },
  computed: {
    second() {
      return this.num(this.seconds);
    },
    minute() {
      return this.num(this.minutes);
    },
  },
};
</script>

<style scoped>
body {
  background: #f1f1f1;
}
.pay_top {
  margin-top: 3rem;
  background: #ffebcd;
}
.pay_top p {
  color: #bbb;
  line-height: 3rem;
  text-align: center;
  font-size: 0.9rem;
}
.pay_con span {
  float: right;
  color: #666;
}
.pay_con span i {
  color: rgb(0, 200, 0);
}
.pay_con p {
  background: #fff;
  color: #666;
  padding: 0rem 0.6rem;
  margin-bottom: 0;
  line-height: 2.5rem;
  border-bottom: 1px solid #f1f1f1;
  font-family: "Microsoft Yahei";
}
.pay_way {
  margin-top: .5rem;
  margin-bottom: 0;
  line-height: 2rem;
  color: #333;
  font-family: "Microsoft Yahei";
  padding: 0 1rem;
}
.pay_con .iconfont {
  font-size: 1.6rem;
  padding: 0 0.2rem;
}
.icon-weixinzhifu {
  color: rgb(0, 200, 0);
}
.icon-ziyuan {
  color: rgb(0, 158, 242);
}
.icon-selected {
  float: right;
}
.pay_bot {
  width: 100%;
  text-align: center;
  line-height: 2.5rem;
  border-radius: 0.2rem;
  margin-top: 0.8rem;
  color: #fff;
  background: #3190e8;
  border: none;
  outline: none;
  position: fixed;
  bottom:0.4rem;
}
</style>
